﻿using System;
using System.Threading.Tasks;

namespace MultipleThreadTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine($"{Environment.CurrentManagedThreadId} : 1、异步执行耗时操作");
                var task = Task.Run(async () =>
                {
                    Console.WriteLine($"{Environment.CurrentManagedThreadId} : 异步耗时操作");
                    await Task.Delay(1000 * 5);
                    Console.WriteLine($"{Environment.CurrentManagedThreadId} : 异步结束");
                });
                Console.WriteLine($"{Environment.CurrentManagedThreadId} : 主线程等待");
                await task;
                Console.WriteLine($"{Environment.CurrentManagedThreadId} : 主线程继续");

                Console.WriteLine();
                Console.WriteLine($"{Environment.CurrentManagedThreadId} : 2、异步执行异常操作");

                Console.WriteLine($"{Environment.CurrentManagedThreadId} : 主线程等待");
                try
                {
                    await Task.Run(async () =>
                    {
                        Console.WriteLine($"{Environment.CurrentManagedThreadId} : 异步异常操作");
                        await Task.Delay(1000 * 2);
                        Console.WriteLine($"{Environment.CurrentManagedThreadId} : 异步抛错");
                        throw new InvalidOperationException();
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{Environment.CurrentManagedThreadId} : 主线程异常处理");
                    Console.WriteLine($"{Environment.CurrentManagedThreadId} : Catch Exception:{ex}");
                    Console.WriteLine();
                }

                Console.WriteLine($"{Environment.CurrentManagedThreadId} : 主线程结束...");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{Environment.CurrentManagedThreadId} : {ex}");
            }
            finally
            {
                Console.ReadKey();
            }
        }
    }
}
